<template>
  <div>
    <Breadcrumb></Breadcrumb>
    <el-card class="box-card">
      <el-row>
        <el-alert title="注意: 只允许为第三级分类设置相关参数!" type="warning" show-icon></el-alert>
      </el-row>

      <div class="block">
        <span class="demonstration">选择商品分类:&emsp; &emsp;</span>
        <el-cascader
          expandTrigger="hover"
          v-model="selectedCateKeys"
          :options="cateList"
          :props="cateProps"
          @change="handleChange"
        ></el-cascader>
      </div>

      <!-- Tabs标签页 -->
      <el-tabs type="border-card" v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button
            type="primary"
            plain
            :disabled="isButtonDidsabled"
            @click="dialogFormVisible = true"
          >添加参数</el-button>

          <!-- border是竖边框,stripe是斑马纹 -->
          <el-table style="width: 100%" :data="manyTableData" border stripe>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template v-slot="scope">
                <el-tag
                  v-for="(item,key) in scope.row.attr_vals"
                  :key="key"
                  closable
                  :disable-transitions="false"
                  @close="handleClose(key,scope.row)"
                >{{item}}</el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template v-slot="scope">
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  @click="getEnditData(scope.row)"
                >修改</el-button>&emsp;&emsp;&emsp;&emsp;
                <el-button
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  q
                  @click="delEnditData(scope.row.attr_id)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 静态属性 -->
        <el-tab-pane label="静态属性" name="only">
          <el-button
            type="primary"
            plain
            :disabled="isButtonDidsabled"
            @click="dialogFormVisible = true"
          >添加属性</el-button>
          <!-- border是竖边框,stripe是斑马纹 -->
          <el-table style="width: 100%" :data="onlyTablyData" border stripe>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template v-slot="scope">
                <el-tag
                  v-for="(item,key) in scope.row.attr_vals"
                  :key="key"
                  closable
                  :disable-transitions="false"
                  @close="handleClose(key,scope.row)"
                >{{item}}</el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template v-slot="scope">
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  @click="getEnditData(scope.row)"
                >修改</el-button>&emsp;&emsp;&emsp;&emsp;
                <el-button
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  q
                  @click="delEnditData(scope.row.attr_id)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
      <!-- 添加参数对话框 -->
      <el-dialog title="添加动态参数" :visible.sync="dialogFormVisible" close>
        <el-form ref="manyFrom" label-width="80px" :model="manyFrom" :rules="rules">
          <el-form-item label="动态参数" prop="attr_name">
            <el-input v-model="manyFrom.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="dialogForm">确 定</el-button>
        </div>
      </el-dialog>

      <!-- 修改参数对话框 -->
      <el-dialog title="修改动态参数" :visible.sync="enditFormVisible" close>
        <el-form ref="enditData" label-width="80px" :model="enditData" :rules="enditFrom">
          <el-form-item label="动态参数" prop="attr_name">
            <el-input v-model="enditData.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="enditFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="coseEnditData">确 定</el-button>
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import {
  getCateListData,
  getHandleChange,
  getAddAttr,
  getEnditDataList,
  coseEnditDataList,
  getRemoveData,
  getSaveAttrVals
} from "@/api/Goods/params.js";
import Breadcrumb from "@/components/Breadcrumb";
export default {
  components: { Breadcrumb },
  data() {
    return {
      cateList: [], //商品分类参数列表数据
      selectedCateKeys: [], //选中项绑定的值的id
      //配置级联菜单中数据如何展示
      cateProps: {
        value: "cat_id",
        label: "cat_name",
        children: "children"
      },
      activeName: "many", //默认在动态参数页面
      manyTableData: [], //获取动态参数得到的数据
      onlyTablyData: [], //获取静态属性得到的数据
      dialogTableVisible: false,
      dialogFormVisible: false, //添加动态参数开关
      enditFormVisible: false, //修改动态参数开关
      enditData: {
        attr_name: ""
      }, //修改动态参数中的对象

      //添加参数的表单对象
      manyFrom: {
        attr_name: ""
      },
      //   添加参数的表单验证
      rules: {
        attr_name: [
          { required: true, message: "参数名称不能为空", trigger: "blur" }
        ]
      },
      //修改参数中的表单验证
      enditFrom: {
        attr_name: [
          { required: true, message: "参数名称不能为空", trigger: "blur" }
        ]
      },

      inputVisible: false,
      inputValue: ""
    };
  },
  methods: {
    //获取商品参数列表的数据
    async getCateList() {
      let { data: res } = await getCateListData();
      this.cateList = res.data;
      console.log(this.cateList);
    },
    //获取动态参数的数据
    async handleChange() {
      //当用户在级联菜单中选择内容改变时触发
      console.log(this.selectedCateKeys);
      let { data: res } = await getHandleChange(this.cateId, {
        sel: this.activeName
      });

      console.log(res);
      if (res.meta.status !== 200) {
        return this.$message.error("获取参数列表失败");
      }
      this.$message.success("获取参数列表成功");

      //将获取到的数据中的attr_vals字符串转换为数组
      res.data.forEach(item => {
        console.log(item);
        item.attr_vals = item.attr_vals ? item.attr_vals.split(",") : [];
        console.log(item.attr_vals);
        item.inputVisible = false; //v-if不执行
        item.inputValue = "";
      });

      if (this.activeName == "many") {
        //获取到的是动态参数数据
        this.manyTableData = res.data;
      } else if (this.activeName == "only") {
        this.onlyTablyData = res.data;
      }
    },
    // 监听Tab标签栏切换
    handleClick() {
      console.log(this.activeName);
      this.handleChange();
    },

    //点击dialogForm事件完成添加动态参数
    dialogForm() {
      console.log(this.manyFrom.attr_name);
      this.$refs.manyFrom.validate(async valid => {
        if (valid) {
          let res = await getAddAttr(this.cateId, {
            attr_name: this.manyFrom.attr_name,
            attr_sel: this.activeName
          });

          console.log(res);
          if (res.meta.msg != "创建成功") {
            return this.$message.error("添加参数失败");
          }
          this.$message.success("添加参数成功");
          this.dialogFormVisible = false;
          this.manyFrom.attr_name = "";
          this.handleChange();
        }
      });
    },
    //打开修改时出现的对话框并把当前数据中的attr_name上传到input框中
    async getEnditData(value) {
      console.log(value);
      this.enditData = value;
      console.log(this.enditData);
      const res = await getEnditDataList(this.cateId, value.attr_id);
      console.log(res);
      if (res.data.meta.msg != "获取成功") {
        this.$message.error("请求参数失败");
      }
      this.$message.success("请求参数成功");
      this.enditFormVisible = true;
      this.enditData.attr_name = value.attr_name;
    },
    //点击关闭修改时的对话框并且把编辑的内容进行修改实现实时监听
    coseEnditData() {
      this.$refs.enditData.validate(async valid => {
        if (valid) {
          console.log(valid);
          console.log(this.manyTableData);
          const res = await coseEnditDataList(
            this.cateId,
            this.enditData.attr_id,
            {
              attr_name: this.enditData.attr_name,
              attr_sel: this.activeName
            }
          );
          console.log(res);

          if (res.meta.msg != "更新成功") {
            this.$message.error("参数更新失败");
          }
          this.$message.success("参数更新成功");
          this.enditFormVisible = false;
          this.handleChange();
        }
      });
    },

    //删除参数列表
    async delEnditData(attr_id) {
      console.log(attr_id);
      const { data: res } = await getRemoveData(this.cateId, attr_id);
      console.log(res);
      if (res.meta.msg != "删除成功") {
        this.$message.error("参数删除失败");
      }
      this.$message.success("参数删除成功");
      this.handleChange();
    },

    //删除tag标签的参数列表
    handleClose(key, row) {
      console.log(key, row);
      row.attr_vals.splice(key, 1);
      console.log(row.attr_vals);
      this.saveAttrVals(row);
    },

    async saveAttrVals(row) {
      console.log(row);
      const res= await getSaveAttrVals(this.cateId, row.attr_id, {
        attr_name: row.attr_name,
        attr_sel: row.attr_sel,
        //   Split()方法是切割成数组的形式，
        // Join()方法是将数组转换成字符串。

        attr_vals: row.attr_vals.join(",")
      });

      console.log(res);
      if (res.meta.status !== 200) {
        return this.$message.error("修改参数项失败！");
      }

      this.$message.success("修改参数项成功！");
    },

    // 按下回车或者焦点出发时完成修改tag标签中参数的修改
    handleInputConfirm(row) {
      console.log(row);
      let inputValue = row.inputValue;
      if (inputValue) {
        row.attr_vals.push(inputValue);
      }
      row.inputVisible = false;
      row.inputValue = "";
      this.saveAttrVals(row);
    },

    showInput(row) {
      console.log(row);
      row.inputVisible = true;
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    }
  },
  created() {
    this.getCateList();
  },
  computed: {
    isButtonDidsabled() {
      return this.selectedCateKeys.length !== 3;
    },

    //获取三级id
    cateId() {
      if (this.selectedCateKeys.length === 3) {
        return this.selectedCateKeys[this.selectedCateKeys.length - 1];
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.el-card {
  margin-top: 20px;
}
.block {
  margin-top: 20px;
}
.el-tabs {
  margin-top: 20px;
  .el-button {
    font-size: 10px !important;
    margin: 0 20px;
  }
  /deep/.el-button[data-v-357a4174] {
    margin: 0 0 0 !important;
  }
}
/deep/.el-table__empty-block {
  width: 100% !important;
}

.el-table {
  margin-top: 20px;
}

.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
.block {
  display: flex;
  align-items: center;
}
</style>